package online.siwu.bmi

import android.annotation.SuppressLint
import android.content.Context
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
import java.text.DecimalFormat

@SuppressLint("SetTextI18n")
class MainActivity : AppCompatActivity() {

    private var isExit = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        btStart.setOnClickListener {
            if (etHeight.text.toString() == "" || etWeight.text.toString() == "")
                Toast.makeText(this, "身高和体重不能为空！！！", Toast.LENGTH_SHORT).show()
            else
                showBmi()
        }

        btReset.setOnClickListener {
            etHeight.setText("")
            etWeight.setText("")
            tlTable.visibility = View.INVISIBLE
        }
    }

    fun showBmi() {
        val fmt = DecimalFormat("##.##")
        val str: String
        val fBmi = getBmi()

        if (fBmi < 18.5)
            str = "过轻"
        else if (18.5 <= fBmi && fBmi < 24)
            str = "健康"
        else if (24 <= fBmi && fBmi < 27)
            str = "过重"
        else if (27 <= fBmi)
            str = "肥胖"
        else
            str = "错误"

        tvBmi.text = "${fmt.format(fBmi)}【$str】"
        tlTable.visibility = View.VISIBLE
        val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS)
    }

    fun getBmi(): Float {
        val h = etHeight.text.toString().toFloat() / 100
        val w = etWeight.text.toString().toFloat()

        return w / (h * h)
    }

    //双击退出
    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            val handler = Handler()

            if ((!isExit)) {
                isExit = true
                toast("再按一次退出APP")
                handler.postDelayed({ isExit = false }, 1000 * 2) //x秒后没按就取消

            } else {
                finish()
                System.exit(0)
            }
        }
        return false
    }
}
